<template>
  <form action="javascript:void(0)" :class="warpClass?warpClass:''">
    <div class="search-wrap">
      <div class="input-wrap">
        <i class="mintui mintui-search"></i>
        <input type="search" :placeholder="ph" v-model.trim="searchResult" @keyup.13="opertation" @focus="focus">
        <i v-show="clearVisible" class="zhk-sbylx" @click="clearInput"></i>
      </div>
      <a class="mint-searchbar-cancel" :class="{ hide: styleHide }" @click.prevent="opertation">搜索</a>
    </div>
  </form>
</template>

<script>
import Vue from "vue";
export default {
  name: "searchBar",
  data() {
    return {
      searchResult: "",
      styleHide: true,
      ph: this.placeholder ? this.placeholder : "搜索",
      clearVisible: false
    };
  },
  props: {
    placeholder: String,
    warpClass: String,
    clearVal: Date
  },
  methods: {
    focus() {
      if (this.searchResult) {
        this.clearVisible = true;
      } else {
        this.clearVisible = false;
      }
    },
    clearInput() {
      this.searchResult = "";
    },
    opertation() {
      this.styleHide = true;
      this.$emit("search", this.searchResult);
    }
  },
  watch: {
    searchResult() {
      if (this.searchResult.length) {
        this.styleHide = false;
        this.clearVisible = true;
      } else {
        this.styleHide = true;
        this.clearVisible = false;
        this.$emit("search", this.searchResult); //清空文本框内容是触发搜索
      }
    },
    //通过父组件清空搜索框的值
    clearVal() {
      this.searchResult = "";
    }
  }
};
</script>
<style lang='scss'>
@import "searchBar";
</style>
